<?php


namespace App\Services\Core\Curd;

trait SelectService
{
    public int $page = 1;

    public int $limit = 20;

    private int $offset = 0;

    public array $fields = ['*'];

    public array $orderBy = [];

    public array $like = [];

    public function select()
    {
        # 获取模型对象
        $inst = $this->model->where($this->options);
        # 模糊搜索
        foreach ($this->like as $key => $val) $inst->where($key, 'like', $val);
        # 循环处理排序
        foreach ($this->orderBy as $field => $sort) $inst->orderBy($field, $sort);
        # 分页
        $inst->offset($this->offset)->limit($this->limit);
        # 查询
        return $this->result = $inst->select($this->fields)->get()->makeHidden($this->hidden);
    }

    public function all($options = null)
    {
        # 获取模型对象
        $modelInst = $this->model->where($options ?? $this->options);
        # 循环处理排序
        foreach ($this->orderBy as $field => $sort) $modelInst->orderBy($field, $sort);
        # 查询
        return $this->result = $modelInst->select($this->fields)->get()->makeHidden($this->hidden);
    }

    public function setPagination(array $data = [])
    {
        # 设置页码
        if (isset($data['page'])) $this->page = $data['page'];
        # 设置条目
        if (isset($data['limit'])) $this->limit = $data['limit'];
        # 设置偏移
        $this->offset = ($this->page - 1) * $this->limit;
        # 返回
        return $this;
    }

    public function getPagination(): array
    {
        return [
            'page'  => $this->page,
            'limit' => $this->limit,
            'total' => $this->count(),
        ];
    }

    public function first($options = null)
    {
        return $this->result = $this->model->where($options ?? $this->options)->first();
    }

    public function count($options = null): int
    {
        # 取得实例
        $modelInst = $this->model->where($options ?? $this->options);
        # 模糊搜索
        foreach ($this->like as $key => $val) $modelInst->where($key, 'like', $val);
        # count
        return $this->result = $modelInst->count();
    }

    public function find(int $id)
    {
        return $this->result = $this->model->select($this->fields)->find($id)?->makeHidden($this->hidden);
    }
}
